<template>
  <div>
    <h2>B组件</h2>
    <p>B组件接收到A组件的参数：{{ receivedData }}</p>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import eventBus, { getCachedData, clearCachedData } from "@/utils/eventBus";

const receivedData = ref<string>("");

// 事件处理函数
const handler = (data: string) => {
  console.log("B组件收到数据更新：", data);
  receivedData.value = data;
};

onMounted(() => {
  // 先读取缓存数据，防止错过事件
  const cached = getCachedData();
  if (cached !== null) {
    receivedData.value = cached;
  }

  // 注册监听
  eventBus.on("updateData", handler);
});

onBeforeUnmount(() => {
  // 注销监听
  eventBus.off("updateData", handler);
  // 清理缓存，避免内存泄漏
  clearCachedData();
});
</script>
